﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Test.Common.Log;
using Test.Utility.Extensions;

namespace Test.Cache.MsgQueue.Log
{
    public class DefaultLogQueue : ILogQueue
    {
        /// <summary>
        /// 使用线程安全的ConcurrentQueue实现消息队列
        /// </summary>
        private readonly ConcurrentDictionary<string, ConcurrentQueue<string>> queueDict = new ConcurrentDictionary<string, ConcurrentQueue<string>>();

        private void CreateQueueIfNoKey(string key)
        {
            if (!queueDict.ContainsKey(key))
            {
                queueDict[key] = new ConcurrentQueue<string>();
            }
        }

        /// <summary>
        /// 插入日志队列
        /// </summary>
        /// <param name="level"></param>
        /// <param name="exceptionMsg"></param>
        public void EnQueue(string key, string exceptionMsg)
        {
            CreateQueueIfNoKey(key);
            queueDict[key].Enqueue(exceptionMsg);
        }

        /// <summary>
        /// 插入消息队列
        /// </summary>
        /// <param name="key"></param>
        /// <param name="ex"></param>
        public void EnQueue(string key, Exception ex)
        {
            CreateQueueIfNoKey(key);
            string logMsg = "";
            ex.GetExceptionInfos(out logMsg);
            EnQueue(key, logMsg);
        }


        /// <summary>
        /// 出队
        /// </summary>
        /// <returns></returns>
        public string DeQueue(string key)
        {
            CreateQueueIfNoKey(key);
            string logMsg = null;
            queueDict[key].TryDequeue(out logMsg);
            return logMsg;
        }
    }
}
